<template>
  <div class="bookmarks-manager">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">
          添加书签
        </el-button>
        
        <!-- 批量操作按钮 -->
        <el-button 
          type="danger" 
          icon="el-icon-delete"
          :disabled="!selectedBookmarks.length"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
        
        <el-button 
          type="warning" 
          icon="el-icon-folder"
          :disabled="!selectedBookmarks.length"
          @click="handleBatchCategory"
        >
          批量分类
        </el-button>
      </div>
      
      <div class="toolbar-right">
        <el-input
          v-model="searchQuery"
          placeholder="搜索书签..."
          prefix-icon="el-icon-search"
          clearable
          @clear="handleSearch"
          @input="handleSearch"
          style="width: 300px;"
        ></el-input>
        
        <el-select
          v-model="currentCategory"
          placeholder="选择分类"
          clearable
          @change="handleSearch"
          style="margin-left: 10px; width: 200px;"
        >
          <el-option
            v-for="item in categories"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          >
            <span style="float: left">
              <i :class="item.icon || 'el-icon-folder'" :style="{ color: item.color }"></i>
              {{ item.name }}
            </span>
          </el-option>
        </el-select>
      </div>
    </div>
    
    <!-- 书签列表 -->
    <el-table
      v-loading="loading"
      :data="bookmarks"
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      
      <el-table-column
        prop="title"
        label="标题"
        min-width="200"
      >
        <template slot-scope="scope">
          <div class="bookmark-title-cell">
            <div class="icon-wrapper" @click="handleIconClick(scope.row)">
              <img v-if="scope.row.icon" :src="scope.row.icon" class="bookmark-icon" />
              <i v-else class="el-icon-picture-outline"></i>
            </div>
            <el-link
              :href="scope.row.url"
              target="_blank"
              type="primary"
            >
              {{ scope.row.title }}
            </el-link>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column
        prop="url"
        label="URL"
        min-width="300"
        show-overflow-tooltip
      ></el-table-column>
      
      <el-table-column
        prop="category.name"
        label="分类"
        width="120"
      >
        <template slot-scope="scope">
          <el-tag
            :style="{ backgroundColor: scope.row.category?.color }"
            size="mini"
          >
            {{ scope.row.category?.name }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column
        prop="clickCount"
        label="点击量"
        width="100"
        align="center"
      ></el-table-column>
      
      <el-table-column
        prop="createdAt"
        label="添加时间"
        width="180"
      >
        <template slot-scope="scope">
          {{ new Date(scope.row.createdAt).toLocaleString() }}
        </template>
      </el-table-column>
      
      <el-table-column
        label="操作"
        width="150"
        align="center"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            circle
            @click="handleEdit(scope.row)"
          ></el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            circle
            @click="handleDelete(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination" style="margin-top: 20px; text-align: right;">
      <el-pagination
        background
        :current-page.sync="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size.sync="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSearch"
        @current-change="handleSearch"
      ></el-pagination>
    </div>
    
    <!-- 书签表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @closed="handleDialogClosed"
    >
      <bookmark-form
        ref="bookmarkForm"
        :bookmark="currentBookmark"
        @submit="handleSubmit"
        @cancel="dialogVisible = false"
      ></bookmark-form>
    </el-dialog>
    
    <!-- 批量修改分类对话框 -->
    <el-dialog
      title="批量修改分类"
      :visible.sync="batchCategoryDialogVisible"
      width="400px"
    >
      <el-form :model="batchCategoryForm" label-width="80px">
        <el-form-item label="选择分类">
          <el-select v-model="batchCategoryForm.categoryId" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="item in categories"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            >
              <span style="float: left">
                <i :class="item.icon || 'el-icon-folder'" :style="{ color: item.color }"></i>
                {{ item.name }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchCategoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitBatchCategory" :loading="batchLoading">
          确定
        </el-button>
      </div>
    </el-dialog>
    
    <!-- 隐藏的文件输入用于处理图片上传 -->
    <input
      type="file"
      ref="iconInput"
      accept="image/*"
      style="display: none"
      @change="handleIconFileChange"
    >
  </div>
</template>

<script>
import { mapState } from 'vuex'
import BookmarkForm from '@/components/common/BookmarkForm'
import {
  getBookmarks,
  createBookmark,
  updateBookmark,
  deleteBookmark
} from '@/api/bookmark'

export default {
  name: 'BookmarksManager',
  components: {
    BookmarkForm
  },
  data() {
    return {
      searchQuery: '',
      currentCategory: '',
      currentPage: 1,
      pageSize: 20,
      total: 0,
      bookmarks: [],
      loading: false,
      dialogVisible: false,
      currentBookmark: null,
      selectedBookmarks: [],
      batchCategoryDialogVisible: false,
      batchCategoryForm: {
        categoryId: ''
      },
      batchLoading: false,
      currentEditingBookmark: null
    }
  },
  computed: {
    ...mapState(['categories']),
    dialogTitle() {
      return this.currentBookmark ? '编辑书签' : '添加书签'
    }
  },
  created() {
    // 获取分类列表
    this.$store.dispatch('fetchCategories')
    // 获取书签列表
    this.handleSearch()
  },
  mounted() {
    // 添加粘贴事件监听
    document.addEventListener('paste', this.handlePaste);
  },
  beforeDestroy() {
    // 移除粘贴事件监听
    document.removeEventListener('paste', this.handlePaste);
  },
  methods: {
    async handleSearch() {
      this.loading = true
      try {
        const params = {
          page: this.currentPage,
          limit: this.pageSize,
          search: this.searchQuery,
          category: this.currentCategory
        }
        
        const response = await getBookmarks(params)
        this.bookmarks = response.data
        this.total = response.total
      } catch (error) {
        this.$message.error('获取书签列表失败')
      } finally {
        this.loading = false
      }
    },
    handleAdd() {
      this.currentBookmark = null
      this.dialogVisible = true
    },
    handleEdit(bookmark) {
      this.currentBookmark = { ...bookmark }
      this.dialogVisible = true
    },
    handleDelete(bookmark) {
      this.$confirm('确认删除该书签吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true;
          await deleteBookmark(bookmark._id);
          this.$message.success('删除成功');
          await this.handleSearch();
        } catch (error) {
          console.error('删除书签失败:', error);
          this.$message.error(error.response?.data?.message || '删除失败');
        } finally {
          this.loading = false;
        }
      }).catch(() => {
        // 用户取消删除，不需要处理
      });
    },
    async handleSubmit(formData) {
      try {
        if (this.currentBookmark) {
          await updateBookmark(this.currentBookmark._id, formData)
          this.$message.success('更新成功')
        } else {
          await createBookmark(formData)
          this.$message.success('添加成功')
        }
        
        this.dialogVisible = false
        this.handleSearch()
      } catch (error) {
        this.$message.error(error.message || '操作失败')
      }
    },
    handleDialogClosed() {
      this.currentBookmark = null
      this.$refs.bookmarkForm && this.$refs.bookmarkForm.$refs.form.resetFields()
    },
    handleSelectionChange(val) {
      this.selectedBookmarks = val;
    },
    handleBatchDelete() {
      if (!this.selectedBookmarks.length) return;
      
      this.$confirm(`确认删除选中的 ${this.selectedBookmarks.length} 个书签吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          this.loading = true;
          const deletePromises = this.selectedBookmarks.map(bookmark => 
            deleteBookmark(bookmark._id)
          );
          
          await Promise.all(deletePromises);
          this.$message.success('批量删除成功');
          await this.handleSearch();
        } catch (error) {
          console.error('批量删除失败:', error);
          this.$message.error(error.response?.data?.message || '批量删除失败');
        } finally {
          this.loading = false;
        }
      }).catch(() => {
        // 用户取消删除，不需要处理
      });
    },
    handleBatchCategory() {
      if (!this.selectedBookmarks.length) return;
      this.batchCategoryForm.categoryId = '';
      this.batchCategoryDialogVisible = true;
    },
    async submitBatchCategory() {
      if (!this.batchCategoryForm.categoryId) {
        this.$message.warning('请选择分类');
        return;
      }
      
      try {
        this.batchLoading = true;
        const updatePromises = this.selectedBookmarks.map(bookmark =>
          updateBookmark(bookmark._id, { category: this.batchCategoryForm.categoryId })
        );
        
        await Promise.all(updatePromises);
        this.$message.success('批量修改分类成功');
        this.batchCategoryDialogVisible = false;
        await this.handleSearch();
      } catch (error) {
        console.error('批量修改分类失败:', error);
        this.$message.error(error.response?.data?.message || '批量修改分类失败');
      } finally {
        this.batchLoading = false;
      }
    },
    handleIconClick(bookmark) {
      this.currentEditingBookmark = bookmark;
      this.$refs.iconInput.click();
    },
    handleIconFileChange(event) {
      const file = event.target.files[0];
      if (file && this.currentEditingBookmark) {
        this.processImageFile(file);
      }
      // 清除文件选择，以便能够选择相同的文件
      event.target.value = '';
    },
    handlePaste(event) {
      const items = (event.clipboardData || event.originalEvent.clipboardData).items;
      
      for (const item of items) {
        if (item.type.indexOf('image') === 0) {
          const file = item.getAsFile();
          if (this.currentEditingBookmark) {
            this.processImageFile(file);
          }
          break;
        }
      }
    },
    processImageFile(file) {
      const reader = new FileReader();
      reader.onload = async (e) => {
        try {
          const icon = e.target.result;
          await updateBookmark(this.currentEditingBookmark._id, {
            ...this.currentEditingBookmark,
            icon
          });
          this.$message.success('图标更新成功');
          await this.handleSearch(); // 刷新列表
        } catch (error) {
          console.error('更新图标失败:', error);
          this.$message.error('更新图标失败');
        }
      };
      reader.readAsDataURL(file);
    }
  }
}
</script>

<style lang="less" scoped>
.bookmarks-manager {
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .toolbar-left {
      .el-button {
        margin-right: 10px;
      }
    }
  }
  
  .bookmark-title-cell {
    display: flex;
    align-items: center;
    
    .icon-wrapper {
      width: 24px;
      height: 24px;
      margin-right: 10px;
      border: 1px dashed #dcdfe6;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      
      &:hover {
        border-color: #409EFF;
        color: #409EFF;
      }
      
      .bookmark-icon {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
      
      i {
        font-size: 16px;
        color: #909399;
      }
    }
  }
}
</style> 